#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
@File    : main.py
@Time    : 2025/01/15 14:43:38
@Author  : sunraing
@Contact : sunraing@126.com
@Version : 0.1
@License : BSD 3-Clause License
@Desc    : This script processes video cache directories,
           fixes video files by modifying their headers,
           reads video metadata from JSON files,
           and combines video and audio streams using ffmpeg.
"""

import json
import os
import re
import subprocess


# 去掉视频title信息中不合适的字符与空格
def validate_title(title):
    """
    Remove illegal characters and spaces from the title to make it a valid filename.
    """
    illegal_chars = r"[\/\\\:\*\?\"\<\>\|]"  # '/ \ : * ? " < > |'
    sanitized_title = re.sub(illegal_chars, "-", title).replace(" ", "")
    return sanitized_title


directories = [
    directory
    for directory in os.listdir()
    if os.path.isdir(directory)
    and os.path.exists(os.path.join(directory, "videoInfo.json"))
]


for index, directory in enumerate(directories, start=1):
    ffmpeg_params = ["ffmpeg", "-loglevel", "error"]

    # Process each file in the directory
    for file in os.listdir(directory):
        file_name, file_extension = os.path.splitext(file)
        if file_extension == ".m4s":
            video_file = os.path.join(directory, file)
            fixed_video_file = os.path.join(directory, file_name + ".mp4")
            ffmpeg_params.extend(["-i", fixed_video_file])

            # Read and fix the video file header
            if not os.path.exists(fixed_video_file):
                data = bytes()
                with open(video_file, "rb") as f:
                    data = f.read()
                with open(fixed_video_file, "wb") as f:
                    f.write(data[9:])

    ffmpeg_params.extend(["-acodec", "copy", "-vcodec", "copy"])

    # Read video metadata from JSON file
    json_file = os.path.join(directory, "videoInfo.json")
    with open(json_file, "r") as f:
        metadata = json.load(f)
        group_title = validate_title(metadata["groupTitle"])
        title = validate_title(metadata["title"])
        output_filename = title + ".mp4"

    # Determine output path
    if group_title == title:
        output_path = output_filename
    else:
        if not os.path.exists(group_title):
            os.makedirs(group_title)
        output_path = os.path.join(group_title, output_filename)

    ffmpeg_params.append(output_path)

    print(f"\r进度: {index}/{len(directories)}", end="")
    if not os.path.exists(output_path):
        subprocess.call(ffmpeg_params)

print("\n视频处理完成。")
